package com.erpoa.listener;

import cn.hutool.json.JSONUtil;
import com.erpoa.annotation.DataBase;
import com.erpoa.constants.DataSourceNames;
import com.erpoa.constants.MqConstant;
import com.erpoa.entity.LogicBean;
import com.erpoa.entity.MgUser;
import com.erpoa.mapper.CarDataMapper;
import com.erpoa.service.CarDataService;
import com.erpoa.utils.*;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.TemplateEngine;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;


@Component
@Slf4j
public class Wmsqueue54Listener {

    private static final Logger logger = LoggerFactory.getLogger(Wmsqueue54Listener.class);


    @Autowired
    private CarDataMapper carDataMapper;
    @Autowired
    private CarDataService carDataService;

    @Autowired
    MailUtil mailUtil;
    // 注入模板引擎
    @Autowired
    TemplateEngine templateEngine;
    @Resource
    private RedisUtil redisUtil;


    @Value("${spring.redis.reidsexpire}")
    private Long reidsexpire;


    @Value("${spring.mq.error}")
    private String senderto;

    /**
     * 监听队列的消息
     *
     * @param msg 消息内容
     * @RabbitListener(queues = MqConstant.QUEUE_TEST_HELLO) 代表监听的队列名称
     */
    @RabbitListener(queues = MqConstant.QUEUE_TEST_HELLO)
    @RabbitHandler
    @DataBase(DataSourceNames.WMS)
    public void getTestMsg(String msg) {
        log.info("---------->接收到的消息:{}", msg);
    }

    /**
     * 获取到的延时消息
     * 这里接收到消息进行对应的业务处理(例如:登录该程序，进行一个短信通知)
     *
     * @param msg
     */
    //  @RabbitListener(queues = MqConstant.SYS_ORDER_RECEIVE_QUEUE)
    //  @RabbitHandler
    @DataBase(DataSourceNames.WMS)
    @Transactional
    public void getdelayMsg(String msg, Channel channel, Message message) throws IOException {


        try {
            System.out.println("线程:" + Thread.currentThread().getId() + "请求开始：" + "wmsqueue5队列监听器接收消息时间:{},消息内容:{}" + DateUtils.getTime() + msg);
            //JSONUtil.parseObj();
            //TODO 具体业务
            LogicBean logicBean = JSONUtil.toBean(msg, LogicBean.class);
            String mBarcode = logicBean.getLogisticNo();
            String trayNumber = logicBean.getTrayNumber();
            MgUser mgUser = new MgUser();
            mgUser.setsCode(logicBean.getScanners());
            mgUser.setsName(logicBean.getScannName());
            int rowdetail = this.carDataMapper.updatesqlDetailSecond(logicBean, mBarcode, trayNumber, mgUser);
            if (rowdetail <= 0) {
                int updatedata = this.carDataMapper.insertData(logicBean, mgUser);
                SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
                String todayvalue = sdf.format(new Date());
                if (updatedata <= 0) {
                    String errjson = JSONUtil.toJsonStr(logicBean);
                    logger.info(DateUtils.getTime() + "复核失败：" + errjson);


                    redisUtil.del(logicBean.getTrayNumber() + "increcount");
                    redisUtil.del(logicBean.getsName() + "snamecount" + todayvalue);
                    redisUtil.del(logicBean.getsName() + "allqtydesc" + todayvalue);

                    Integer scanTrayBoxCount = this.carDataMapper.selectCountsqlTrayDesc(logicBean);
                    logicBean.setTrayDesc(scanTrayBoxCount.toString());
                    redisUtil.incr(logicBean.getTrayNumber() + "increcount", scanTrayBoxCount);
                    redisUtil.expire(logicBean.getTrayNumber() + "increcount", reidsexpire);

                    Integer detailBoxCount = this.carDataMapper.selectsqlreviewTrayDesc(logicBean);
                    logicBean.setTrayDescAll(detailBoxCount.toString());
                    redisUtil.incr(logicBean.getsName() + "snamecount" + todayvalue, detailBoxCount);
                    redisUtil.expire(logicBean.getsName() + "snamecount" + todayvalue, reidsexpire);

                    Integer allqtydesc = this.carDataMapper.countReviewAllQuery(logicBean);
                    logicBean.setAllQtyDesc(allqtydesc.toString());
                    redisUtil.incr(logicBean.getsName() + "allqtydesc" + todayvalue, allqtydesc);
                    redisUtil.expire(logicBean.getsName() + "allqtydesc" + todayvalue, reidsexpire);

                    redisUtil.del(logicBean.getLogisticNo() + "rechekflag");
                    redisUtil.del(logicBean.getTrayNumber() + "sname");
                    logicBean.setTrayNumber("");
                    logicBean.setScanners("");
                    redisUtil.set(logicBean.getLogisticNo(), JSONUtil.toJsonStr(logicBean), reidsexpire);
                    if (!redisUtil.hasKey(logicBean.getLogisticNo() + "errmail")) {

                        redisUtil.set(logicBean.getLogisticNo() + "errmail", errjson, reidsexpire);
                        this.sendMailutil(senderto, "物流复核失败提醒:"
                                        + logicBean.getLogisticNo(),
                                errjson);
                    }
                    redisUtil.del(logicBean.getLogisticNo() + "rechekflag");
                    throw new PDAException("未复核到相关物流码，请确保日期并已出标签后在操作一次，当前物流码系统拉取到预出日期为：" + logicBean.getDefOutDate());

                } else {
                    LogicBean logicBean1 = this.carDataMapper.checkTrayNoStatus(logicBean);
                    System.out.println("事后查询--：" + logicBean1.toString());
                }

            }
            redisUtil.set(logicBean.getLogisticNo() + "rechekflag", logicBean.getTrayNumber(), reidsexpire);
            if (!redisUtil.hasKey(logicBean.getTrayNumber() + "sname")) {
                redisUtil.set(logicBean.getTrayNumber() + "sname", logicBean.getsName(), reidsexpire);
            }
            if (redisUtil.hasKey(logicBean.getTrayNumber() + "details")) {
                Set<Object> set = redisUtil.sGet(logicBean.getTrayNumber() + "details");
                for (Object set1 : set) {
                    System.out.println("details----------------------" + set1);
                }
            }

            logger.info(DateUtils.getTime() + "复核完成" + logicBean.getLogisticNo() + ":" + JSONUtil.toJsonStr(logicBean));
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();

            if (message.getMessageProperties().getRedelivered()) {
                if (message.getMessageProperties().getDeliveryTag() > 5) {
                    //todo 往错误表插入数据
                    log.error("消息已重复处理失败,拒绝再次接收..." + message.getBody() + e.getMessage());
                    channel.basicReject(message.getMessageProperties().getDeliveryTag(), false); // 拒绝消息
                } else {
                    log.error("消息即将再次返回队列处理..." + message.getBody() + e.getMessage());
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
                }
            } else {
                this.carDataService.wuliuRedis("HJ");
                log.error("消息即将再次返回队列处理..." + message.getBody() + e.getMessage());
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        }
    }


    public boolean sendMailutil(String senderto, String subject, String body) {
        MailBean mailBean = MailBean.getMailBean();
        /**
         * HTML邮件正文发送测试
         */
        mailBean.setSubject(subject);
        String html =
                "<html>"
                        + "<body>"
                        + "<p><h1>" + body + "</h1></p>"
                        + "<p  align='right'><h5>此邮件为系统自动发送，请勿回复！！！</h5></p>"
                        + "</body>"
                        + "</html>";

        mailBean.setText(html);
        //  mailBean.setAttachmentFilename("辅料.xlsx");
        // mailBean.setFile(new FileSystemResource("D:/upload/2020-09-04_辅料EXCEL.xlsx"));
        try {
            mailUtil.sendMailHtmlmq(mailBean, senderto);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

}


